﻿using System;
using System.Collections.Generic;
using System.ServiceModel.Syndication;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Net;
using System.IO;

namespace SimpleRSS
{
    public partial class MainForm : Form
    {
        private string url = String.Empty;
        private List<SyndicationItem> items;
        private delegate void UpdateWindow();

        public MainForm()
        {
            InitializeComponent();
        }

        private void bnLoad_Click(object sender, EventArgs e)
        {
            if (tbFeed.Text.Length > 0)
            {
                url = tbFeed.Text;
                ThreadPool.QueueUserWorkItem(Initialize, url);
            }
        }

        private void Initialize(object state)
        {
            PrintStatus("Loading feed...");

            items = new List<SyndicationItem>();
            
            SyndicationFeed feed = SyndicationFeed.Load(
                new XmlTextReader(url));

            UpdateWindow del = delegate
            {
                if (feed.ImageUrl != null)
                    pictureBoxFeed.ImageLocation = feed.ImageUrl.ToString();
                else
                    pictureBoxFeed.ImageLocation = null;

                lbFeedItems.Items.Clear();
                Text = "[" + feed.Title.Text + "]";

                foreach (SyndicationItem item in feed.Items)
                {
                    items.Add(item);
                    lbFeedItems.Items.Add(item.Title.Text);                    
                }
            };

            Invoke(del);

            PrintStatus("Feed loaded. Ready.");
        }

        private void PrintStatus(string message)
        {
            UpdateWindow del = delegate
            {
                statusLabel.Text = message;
            };

            Invoke(del);
        }

        private void lbFeedItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            webBrowser.DocumentText =
                items[lbFeedItems.SelectedIndex].Summary.Text;

            listBoxEnclosures.Items.Clear();
            foreach (SyndicationLink link in items[lbFeedItems.SelectedIndex].Links)
            {
                Enclosure enc = new Enclosure();
                enc.Title = link.Title;
                enc.Uri = link.Uri;
                listBoxEnclosures.Items.Add(enc);
            }
            bnDownload.Enabled = false;

        }

        private class Enclosure
        {
            public string Title { get; set; }
            public Uri Uri { get; set; }

            public override string ToString()
            {
                return string.Format("{0} - {1}", this.Title, this.Uri.LocalPath);
            }
        }

       

        private void bnDownload_Click(object sender, EventArgs e)
        {
            Enclosure enc = listBoxEnclosures.Items[listBoxEnclosures.SelectedIndex] as Enclosure;
            WebClient client = new WebClient();
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
            string tempFile = Path.GetTempFileName();
            client.DownloadFileAsync(enc.Uri, tempFile, tempFile);
        }

        void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            MessageBox.Show(String.Format("Download of {0} completed",e.UserState.ToString()));
            progressBar1.Value = 0;
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        private void listBoxEnclosures_SelectedIndexChanged(object sender, EventArgs e)
        {
            bnDownload.Enabled = true;
        }
    }
}
